package com.sea.supply.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.codecrane.core.power.service.DictDetailService;
import com.codecrane.core.util.DateUtils;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mchange.lang.DoubleUtils;
import com.sea.data.entity.OrderDetail;
import com.sea.data.service.OrderDetailService;
import com.sea.data.service.OrderService;
import com.sea.product.entity.Product;
import com.sea.product.service.ChannelService;
import com.sea.supply.entity.Buy;
import com.sea.supply.service.BuyService;
import com.sea.supply.service.SupplierService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/sea/supply/buy")
public class BuyController {

    @Autowired
    private BuyService buyService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private ChannelService channelService;
    @Autowired
    private DictDetailService dictDetailService;
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 管理主页面
     * @param model
     * @return
     */
    @RequestMapping("/main")
    public String main(Model model) {
        model.addAttribute("payment", dictDetailService.findByTypeCode("payment_type", null));
        //渠道
        model.addAttribute("channel", channelService.findByCnd(null));
        //供应商
        model.addAttribute("supplier", supplierService.findByCnd(null));

        //颜色
        model.addAttribute("color", dictDetailService.findByTypeCode("product_color", null));
        model.addAttribute("size", dictDetailService.findByTypeCode("product_size", null));

        //订单
        model.addAttribute("order", buyService.findByOrderNo());

        return "/sea/supply/buy/main";
    }

    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/findByCnd")
    public AjaxTableReturn findByCnd(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     Buy buy) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<Buy> list = buyService.findByCnd(buy);
        PageInfo<Buy> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }
    /**
     * 保存
     * @param buy
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public AjaxReturn save(Buy buy) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try{
            if (null != buy && buyService.save(buy) > 0) {
                result.setOk(true).setMsg("保存成功！");
            }
        }catch (DuplicateKeyException e){
            result.setMsg("当前渠道不能重复!");
            return result;
        } catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    /**
     * 拆分
     * @param buy
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/split", method = RequestMethod.POST)
    public AjaxReturn split(Buy buy) {
        AjaxReturn result = Ajax.fail().setMsg("拆分失败！");
        try{
            if (null != buy && buyService.split(buy) > 0) {
                result.setOk(true).setMsg("拆分成功！");
            }
        }catch (RuntimeException e){
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    /**
     * 拆分
     * @param buy
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/supplier", method = RequestMethod.POST)
    public AjaxReturn supplier() {
        AjaxReturn result = Ajax.fail().setMsg("同步失败！");
        try {


            //更新明细的供应商
            orderDetailService.updateSupplierName();
            //更新代采购的供应商
            buyService.updateBuySupplierName();
            result.setOk(true).setMsg("同步成功！");
        } catch (RuntimeException e) {
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }



    /**
     * 生成采购单
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/produce", method = RequestMethod.POST)
    public AjaxReturn produce(@RequestParam("buyIds")Integer[]ids,
                              @RequestParam("supplierName")String supplierName,
                              @RequestParam("produceMoneyType")String produceMoneyType,
                              @RequestParam("paymentType")String paymentType) {
        AjaxReturn result = Ajax.fail().setMsg("生成失败！");
        try{
            if (null != ids && StringUtils.isNotEmpty(supplierName)) {
                String colorResult = buyService.produce(ids, supplierName, produceMoneyType, paymentType);
                result.setOk(true).setMsg("生成成功！<br />"+colorResult);
            }
        }catch (RuntimeException e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/testProduce", method = RequestMethod.GET)
    public void testProduce(@RequestParam("orderId")Integer orderId,
                                  HttpServletResponse response) throws IOException {
        List<Buy> list = buyService.testProduce(orderId);
        // 2. 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("采购模拟订单", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 自定义表头顺序（按需要的顺序排列）
        List<List<String>> customHead = new ArrayList<>();
        customHead.add(Arrays.asList("请购单号"));
        customHead.add(Arrays.asList("渠道"));
        customHead.add(Arrays.asList("SKU"));
        customHead.add(Arrays.asList("商品名称"));
        customHead.add(Arrays.asList("颜色编码"));
        customHead.add(Arrays.asList("颜色"));
        customHead.add(Arrays.asList("尺码(CM)"));
        customHead.add(Arrays.asList("尺码(INCH)"));
        customHead.add(Arrays.asList("尺码"));
        customHead.add(Arrays.asList("装箱量"));
        customHead.add(Arrays.asList("请购数量"));
        customHead.add(Arrays.asList("预计交期"));
        customHead.add(Arrays.asList("箱数"));
        customHead.add(Arrays.asList("货物名称"));
        customHead.add(Arrays.asList("付款方式"));
        customHead.add(Arrays.asList("采购单价"));
        customHead.add(Arrays.asList("总金额"));
        customHead.add(Arrays.asList("单位"));
        customHead.add(Arrays.asList("供应商"));
        // 3. 导出Excel
        EasyExcel.write(response.getOutputStream(), Buy.class)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) // 自动列宽
                .excludeColumnFiledNames(Arrays.asList("id","orderId","detailId","buyDiscount","supplierName","flag","beginDate","endDate","productColorIds","productSizeIds","ids","orderNumber","orderDate","orderProductPrice","timeType","orderStatus","createTime","paymentType","productSku","productPropertyId","productPropertyName","productBigClassId","productBigClassName","productMidClassId","productMidClassName","productClassId","productClassName","productSizeId","productGrossWeight","productWeight","productContainCount","productOutBoxWeight","productOutBoxLength","productOutBoxWidth","productOutBoxHeight","productOutBoxVolume","productVolume","productLength","productWidth","productHeight","productUnit","productCode","productDeclarationName","productUpc","productDay","productFabric","productMaterial","productImg","modifyTime","createNumber","produceNumber","createWareNumber","createPortNumber","wareNumber","stockNumber"))
                .sheet("采购订单")
                .head(customHead)  // 设置自定义表头
                .doWrite(convertDataToCustomOrder(list)); // 转换数据顺序
    }

    /**
     * 将原始数据转换为与自定义表头匹配的顺序
     */
    private List<List<Object>> convertDataToCustomOrder(List<Buy> dataList) {
        List<List<Object>> result = new ArrayList<>();
        for (Buy buy : dataList) {
            List<Object> row = new ArrayList<>();
            row.add(buy.getOrderNo());
            row.add(buy.getOrderChannelName());
            row.add(buy.getOrderSku());
            row.add(buy.getProductName());
            row.add(buy.getProductColorId());
            row.add(buy.getProductColorName());
            row.add(buy.getProductCm());
            row.add(buy.getProductInch());
            row.add(buy.getProductSizeName());
            row.add(buy.getProductPackageNumber());
            row.add(buy.getBuyNumber());
            row.add(buy.getBuyOrderDate());
            row.add(buy.getBoxNumber());
            row.add(buy.getProductClassName());
            row.add(buy.getPaymentType());
            row.add(buy.getProductPrice());
            row.add(buy.getTotalPrice());
            row.add(buy.getProductUnit());
            row.add(buy.getSupplierName());
            result.add(row);
        }
        return result;
    }


    /**
     * 修改交期
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateOderDate", method = RequestMethod.POST)
    public AjaxReturn updateOderDate(@RequestParam("buyIds")Integer[]ids,@RequestParam("buyDate")String buyDate) {
        AjaxReturn result = Ajax.fail().setMsg("生成失败！");
        try{
            if (null != ids && StringUtils.isNotEmpty(buyDate)) {
                buyService.updateOderDate(ids,buyDate);
                result.setOk(true).setMsg("生成成功！");
            }
        }catch (RuntimeException e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/updateSupplierName", method = RequestMethod.POST)
    public AjaxReturn updateSupplierName(@RequestParam("buyIds")Integer[]ids,@RequestParam("supplierName")String supplierName) {
        AjaxReturn result = Ajax.fail().setMsg("生成失败！");
        try{
            if (null != ids && StringUtils.isNotEmpty(supplierName)) {
                buyService.updateSupplierName(ids,supplierName);
                result.setOk(true).setMsg("生成成功！");
            }
        }catch (RuntimeException e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    /**
     * 删除订单
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delOrder", method = RequestMethod.POST)
    public AjaxReturn delOrder(@RequestParam("buyIds")Integer[]ids) {
        AjaxReturn result = Ajax.fail().setMsg("删除失败！");
        try{
            if (null != ids && ids.length!=0) {
                buyService.delOrder(ids);
                result.setOk(true).setMsg("删除成功！");
            }

        }catch (RuntimeException e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    /**
     * 修改交期
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateOderDiscount", method = RequestMethod.POST)
    public AjaxReturn updateOderDiscount(@RequestParam("buyIds")Integer[]ids,@RequestParam("buyDiscount")Double buyDiscount) {
        AjaxReturn result = Ajax.fail().setMsg("生成失败！");
        try{
            if (null != ids && (buyDiscount)>0) {
                buyService.updateOderDiscount(ids,buyDiscount);
                result.setOk(true).setMsg("生成成功！");
            }
        }catch (RuntimeException e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }


    @RequestMapping(value = "/export", method = RequestMethod.GET)
    @ResponseBody
    public void export(HttpServletResponse response, Buy buy) {
        List<Buy> list = buyService.findByCnd(buy);
        String[] title = {"请购单号","渠道","SKU", "商品名称","颜色编码","颜色","尺码(CM)","尺码(INCH)","尺码","装箱量","请购数量","预计交期","供应商"};
        String fileName = "待采购" + DateUtils.dateToString(new Date(), "yyyyMMdd") + ".xls";
        String sheetName = "待采购";
        String[][] content = new String[list.size()][13];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            Buy obj = list.get(i);
            content[i][0] = obj.getOrderNo();
            content[i][1] = obj.getOrderChannelName();
            content[i][2] = obj.getOrderSku();
            content[i][3] = obj.getProductName();
            content[i][4] = obj.getProductColorId();
            content[i][5] = obj.getProductColorName();
            content[i][6] = obj.getProductCm();
            content[i][7] = obj.getProductInch();
            content[i][8] = obj.getProductSizeName();
            content[i][9] = obj.getProductPackageNumber()+"";
            content[i][10] = obj.getBuyNumber()+"";
            content[i][11] = obj.getBuyOrderDate();
            content[i][12] = obj.getSupplierName();
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
